package com.xky.fileupload.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author keying.xia
 * @date 2017/11/30
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);


    @PostMapping(value = "upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file){

        if (file.isEmpty()){
            return "文件为空";
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为:" + fileName);

        //获取文件的后缀名
        String suffixName = fileName.substring(fileName.indexOf("."));
        logger.info("上传的文件名后缀为:"+suffixName);

        //文件上传路径
        String filePath = "D:/fileupload/";

        //中文乱码问题
        fileName = UUID.randomUUID()+suffixName;

        //文件位置
        File dest = new File(filePath+fileName);

        //判断是否存在目录，没有的话 创建
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
            return "上传成功";
        }catch (IOException e){
            e.printStackTrace();
        }catch (IllegalStateException e){
            e.printStackTrace();
        }

        return "上传失败";

    }

}
